package com.uenpay.im.ui.old.activity.chat;

import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.ProgressBar;
import android.widget.TextView;

import com.qiyunxin.android.http.utils.FileUtils;
import com.qiyunxin.android.http.utils.IDownloadProgress;
import com.qiyunxin.android.http.utils.Utils;
import com.qyx.android.database.TalkMsgManager;
import com.qyx.android.protocol.QyxMsg;
import com.uenpay.im.BroadcastAction;
import com.uenpay.im.IMApplication;
import com.uenpay.im.R;
import com.uenpay.im.configuration.APIConfiguration;
import com.uenpay.im.entities.DownloadFileEntity;
import com.uenpay.im.entities.FileType;
import com.uenpay.im.entities.SendFile;
import com.uenpay.im.entities.chatbean.AttachModel;
import com.uenpay.im.entities.chatbean.MsgFileModel;
import com.uenpay.util.app.base.BaseActivity;

import java.io.File;
import java.util.Locale;

/**
 * 下载文件
 *
 * @author SL
 * @date 2014/7/23
 * @copyRight http://www.qiyunxin.com
 */
public class DownloadFileActivity extends BaseActivity {
    private Button download_btn;
    private TextView file_name;
    private TextView file_size;
    private TextView file_type_name;
    private FileUtils fileUtils = new FileUtils(IMApplication.appName);
    private TalkMsgManager takeMsgManager = new TalkMsgManager();
    private QyxMsg message = null;
    private SendFile mSendFile = null;
    private String end = "";
    private String fileDownloadPath = "";
    private ProgressBar download_progressBar;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        isFullScreen = true;
        super.onCreate(savedInstanceState);
    }

    @Override
    public View bindView() {
        return null;
    }

    @Override
    public int bindLayout() {
        return R.layout.download_file_activity;
    }

    @Override
    public void initView(View view) {
        mSendFile = new SendFile();
        initView();
        Bundle mBundle = getIntent().getExtras();
        message = mBundle.getParcelable("mQyxMsg");
        AttachModel attachModel = null;
        MsgFileModel msgFileModel = (MsgFileModel) message.baseContentModel;
        if (msgFileModel != null) {
            attachModel = (AttachModel) msgFileModel
                    .getAttachmentModel();

            fileDownloadPath = APIConfiguration.getFileDownloadPath(
                    attachModel.getFileId(), attachModel.getFileHash());
            file_size.setText(mSendFile.getFileSize(msgFileModel.getSize()));
            file_name.setText(msgFileModel.getName());
            try {
                end = msgFileModel.getName().substring(
                        msgFileModel.getName().indexOf(".") + 1,
                        msgFileModel.getName().length());
            } catch (Exception e) {
            }
            file_type_name.setText(FileType.getFileTypeName(msgFileModel.getName()));
        }
        if (TextUtils.isEmpty(msgFileModel.getName())
                && TextUtils.isEmpty(msgFileModel.getSize())) {
            download_btn.setText(getResources().getString(R.string.no_file));
            download_progressBar.setVisibility(View.GONE);
            download_btn.setBackgroundResource(R.drawable.button_bg_gray);
            download_btn.setTextColor(getResources()
                    .getColor(R.color.CLR8C8C8C));
            download_btn.setEnabled(false);
        } else {
            if (TextUtils.isEmpty(attachModel.getFileLocalPath())) {
                File file = null;
                try {
                    file = fileUtils.getFile(attachModel.getFileHash(), end);
                    if (file.exists() && file.length() > 0) {
                        download_btn.setText(getResources().getString(
                                R.string.open_file));
                        download_progressBar.setVisibility(View.GONE);
                    } else {
                        download_btn.setText(getResources().getString(
                                R.string.download_file));
                        download_progressBar.setVisibility(View.VISIBLE);
                    }
                } catch (Exception e) {
                }
            } else {
                download_btn.setText(getResources().getString(
                        R.string.open_file));
            }
        }

        download_btn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (download_btn.getText().equals(
                        getResources().getString(R.string.download_file))) {

                    if (!TextUtils.isEmpty(end)
                            && !TextUtils.isEmpty(fileDownloadPath)) {
                        boolean is_have_network = Utils
                                .isNetworkConnected(IMApplication
                                        .getAppContext());
                        if (!is_have_network) {
                            IMApplication.showToast(getResources().getString(
                                    R.string.no_network));
                            return;
                        }
                        download_btn.setEnabled(false);
                        downloadFile();
                    }
                } else if (download_btn.getText().equals(
                        getResources().getString(R.string.open_file))) {
                    openFileBySys();
                }
            }
        });
    }

    private void downloadFile() {
        new Thread(new Runnable() {
            @Override
            public void run() {
                String localFilePath = "";
                String fileName = "";
                MsgFileModel msgFileModel = (MsgFileModel) message.baseContentModel;
                if (msgFileModel != null) {
                    fileName = msgFileModel.getName();
                }
                localFilePath = fileUtils.downloadFile1(fileDownloadPath,
                        end, fileName, new IDownloadProgress() {
                            @Override
                            public void onProgress(long total, long down_total) {
                                Message msg = myHandler.obtainMessage();
                                DownloadFileEntity download_entity = new DownloadFileEntity();
                                download_entity.total = total;
                                download_entity.download_total = down_total;
                                msg.what = 1;
                                msg.obj = download_entity;
                                myHandler.sendMessage(msg);
                            }
                        });
                if (TextUtils.isEmpty(localFilePath)) {
                    Message msg = myHandler.obtainMessage();
                    msg.what = 2;
                    myHandler.sendMessage(msg);
                    IMApplication.showToast(getResources().getString(
                            R.string.download_file_failure));
                    return;
                } else {
                    message.baseContentModel.getAttachmentModel().setFileLocalPath(localFilePath);
                    Message msg = myHandler.obtainMessage();
                    msg.what = 0;
                    myHandler.sendMessage(msg);
                    takeMsgManager.updateMsgFilePath(message._id, localFilePath);
                    Intent intent = new Intent(
                            BroadcastAction.UPDATE_DOWNLAOD_FILE_STAUS);
                    Bundle bundle = new Bundle();
                    bundle.putParcelable("msg", message);
                    intent.putExtras(bundle);
                    sendBroadcast(intent);
                }
            }
        }).start();
    }

    private void openFileBySys() {
        try {
            if (TextUtils.isEmpty(end)) {
                IMApplication.showToast(getResources().getString(
                        R.string.can_not_open_file));
            }
            File file = new File(message.baseContentModel.getAttachmentModel().getFileLocalPath());
            Intent intent = new Intent();
            intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            intent.setAction(Intent.ACTION_VIEW);
            String type = getMIMEType(file);
            intent.setDataAndType(/* uri */Uri.fromFile(file), type);
            startActivity(intent);
        } catch (Exception e) {
            IMApplication.showToast(getResources().getString(
                    R.string.can_not_open_file));
        }
    }

    private String getMIMEType(File file) {
        String type = "*/*";
        String fName = file.getName();
        int dotIndex = fName.lastIndexOf(".");
        if (dotIndex < 0) {
            return type;
        }
        String end = fName.substring(dotIndex, fName.length()).toLowerCase(
                Locale.getDefault());
        if (end == "")
            return type;
        for (int i = 0; i < FileUtils.MIME_MapTable.length; i++) {
            if (end.equals(FileUtils.MIME_MapTable[i][0]))
                type = FileUtils.MIME_MapTable[i][1];
        }
        return type;
    }

    private Handler myHandler = new Handler(new Handler.Callback() {

        @Override
        public boolean handleMessage(Message msg) {
            if (msg.what == 0) {
                if (download_progressBar != null) {
                    download_progressBar.setVisibility(View.GONE);
                    download_btn.setText(getResources().getString(
                            R.string.open_file));
                    download_btn.setEnabled(true);
                }
            } else if (msg.what == 1) {
                DownloadFileEntity download_entity = (DownloadFileEntity) msg.obj;
                if (download_entity.total > 0) {
                    download_progressBar
                            .setProgress((int) (download_entity.download_total * 100 / download_entity.total));
                }
            } else if (msg.what == 2) {
                download_btn.setEnabled(true);
            }

            return false;
        }
    });

    protected void initView() {
        ((TextView) findViewById(R.id.title_textview)).setText(getResources()
                .getString(R.string.file_detail));
        file_size = (TextView) findViewById(R.id.download_file_size);
        file_name = (TextView) findViewById(R.id.download_file_name);
        file_type_name = (TextView) findViewById(R.id.received_file_type_name);
        download_btn = (Button) findViewById(R.id.download_file_btn);
        download_progressBar = (ProgressBar) findViewById(R.id.download_progressBar);
    }

    protected void initListener() {
    }
}
